<template>
  <div class="edu-page-warp">
      <ConditionCard body-style="padding: 24px 24px 6px;" @search="search" @reset="reset">
        <el-form :model="condition" label-width="140px" ref="conditionForm">
          <el-row :gutter="24">
            <el-col :span="9">
              <el-form-item :label="$t('principal.principalStartTime') + ':'" prop="startDate">
                <el-date-picker v-model="condition.startDate" :placeholder="$t('common.pla.pleaseSelect')"
                   type="datetime" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" align="right" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="9">
              <el-form-item :label="$t('principal.endTime') + ':'" prop="endDate">
                <el-date-picker v-model="condition.endDate" :placeholder="$t('common.pla.pleaseSelect')"
                   type="datetime" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" align="right" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </ConditionCard>

      <el-card shadow="never" body-style="padding: 24px;">
        <div class="edu-page-title" style="margin-bottom: 20px;">{{$t("principal.principalReplacementList")}}</div>
        <div class="clearfix" style="margin-bottom: 16px;">
          <div class="float-left">
              <el-input style="width: 240px;"   v-model="condition.keyWords" :placeholder="$t('principal.principalplaceholder')" suffix-icon="el-icon-search" @change="search" />
          </div>
          <div class="float-right">
            <el-button type="danger" @click="del">{{$t("common.btn.delete")}}</el-button>
            <el-button type="primary" @click="add">{{$t("common.btn.add")}}</el-button>
          </div>
        </div>
        <edu-table :data="tableData" :order="false" :pageNum="page.pageNum_" :selection="false"
          :pageSize="page.pageSize_" :total="page.total_" @page-change="pageChange" ref="principalTable" :isRowClickChangeRowSelection="false">
          <el-table-column type="selection" width="80" :selectable="selectable"/>
          <edu-table-column :label="$t('principal.principalName')" width="80" align="center" prop="name">
          </edu-table-column>
          <edu-table-column :label="$t('principal.startTime')" min-width="150" align="center" prop="startDate">
          </edu-table-column>
          <edu-table-column :label="$t('principal.endTime')" min-width="150" align="center" prop="endDate">
          </edu-table-column>
          <edu-table-column :label="$t('principal.status')" min-width="80" align="center">
            <template slot-scope="scope">
              <div v-if="statusMap[scope.row.status]">
                <el-tag size="mini" :type="statusMap[scope.row.status].type">
                  {{statusMap[scope.row.status].label}}</el-tag>
              </div>
            </template>
          </edu-table-column>
          <edu-table-column :label="$t('common.text.operation')" align="center" min-width="100">
            <template slot-scope="scope">
              <div>
                <el-button type="text" size="mini" @click.stop="editOperation(scope.row)" :disabled="scope.row.isEditDisable" >{{$t('common.btn.edit')}}</el-button>
              </div>
            </template>
          </edu-table-column>
        </edu-table>
      </el-card>
      <div v-if="showPrincipalDialog">
        <!-- 新增编辑弹框 -->
        <edu-dialog :title="dialogTitle" size="small" :visible.sync="showPrincipalDialog" :autoHeight="false"
          :confirmBtnText="$t('common.btn.confirm')" :close-on-click-modal="false" @close="close" @confirm="confirm('principalInformationForm')">
          <el-form :model="principalInformation" ref="principalInformationForm" :rules="rules" label-width="120px" label-position="right"
            size="small">
            <el-row>
              <el-col :span="19">
                <el-form-item :label="$t('principal.principalName') + ':'" prop="keyWords">
                  <el-select v-model="principalInformation.keyWords" filterable  remote :remote-method="getSelectOption" :loading="loading"  
                    :placeholder="$t('common.pla.pleaseSelect')" :disabled="!dialogIsAdd">
                    <el-option
                      v-for="item in selectOptions"
                      :key="item.key"
                      :label="item.label"
                      :value="item.label">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="19">
                <el-form-item :label="$t('principal.startTime') + ':'" prop="startDate">
                  <el-date-picker v-model="principalInformation.startDate" :placeholder="$t('common.pla.pleaseSelect')"
                     type="datetime" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" align="right" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="19">
                <el-form-item :label="$t('principal.endTime') + ':'" prop="endDate">
                  <el-date-picker v-model="principalInformation.endDate" :placeholder="$t('common.pla.pleaseSelect')"
                     type="datetime" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" align="right" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </edu-dialog>
      </div>
  </div>
</template>
<script>
  import {findPrincipalManagementList, addPrincipalManagementList, updatePrincipalManagementList, deletePrincipalManagementList, findTeacherInfoList} from 'common/src/api/graduationManagement/graduationManage';
  export default {
    data(){
      return {
        condition: {
          startDate: '',
          endDate: '',
          keyWords: ''
        },
        tableData: [],
        page: {
          pageNum_: 1,
          pageSize_: 20,
          total_: 0
        },
        statusMap: {
          0: {
            label: this.$t('principal.notActive'),
            type: 'danger'
          },
          1: {
            label: this.$t('principal.actived'),
            type: 'success'
          },
          2: {
            label: this.$t('principal.expired'),
            type: 'info'
          }
        },
        dialogTitle: '',
        dialogIsAdd: false,
        showPrincipalDialog: false,
        principalInformation: { // 弹出框绑定信息
          keyWords: '',
          startDate: '',
          endDate: '',
        },
        selectOptions: [],
        loading: false,
        rules: {
          keyWords: [{
            required: true,
            message: this.$t('principal.validName')
          }],
          startDate: [{
            required: true,
            message: this.$t('principal.validStartTime')
          }]
        }
      }
    },
    created() {
      this.query();
    },
    methods: {
      search() {
        if (this.condition.startDate && this.condition.endDate) {
          let startTime = this.formateTimeToStr(this.condition.startDate);
          let endTime = this.formateTimeToStr(this.condition.endDate);
          if (startTime > endTime) {
            this.$message({
              message: this.$t('principal.validStartTimeAndEndTime'),
              type: 'warning'
            });
            return;
          }
        }
        this.page.pageNum_ = 1;
        this.query();
      },
      reset() {
        this.$refs.conditionForm.resetFields();
        this.page.pageNum_ = 1;
        this.query();
      },
      query({
        pageSize,
        pageNum
      } = {}) {
        let param = {
          pageNum_: pageNum || this.page.pageNum_,
          pageSize_: pageSize || this.page.pageSize_
        }
        for(let attr in this.condition) {
          if (this.condition[attr]) {
            param[attr] = this.condition[attr];
          }
        }
        findPrincipalManagementList(param).then(res =>{
          if (res && res.code === 200) {
            let data = res.data || {};
            let list = data.list || [];
            this.updateTableData(list);
            this.tableData = list || [];
            this.page.total_= data.total_ || 0;
            this.page.pageNum_ = param.pageNum_;
            this.page.pageSize_ = param.pageSize_;
          }
        }).catch(() =>{
          this.tableData = [];
          this.page.total_= 0;
          this.page.pageNum_ = 1;
          this.page.pageSize_ = param.pageSize_;
        })
      },
      updateTableData(data) {
        let currentTime = new Date().getTime();
        data.forEach(item =>{
          let endTime = this.formateTimeToStr(item.endDate);
          if (endTime && currentTime > endTime) {
            item.isEditDisable = true;
          }else {
            item.isEditDisable = false;
          }
        })
      },
      pageChange(pageOption) {
        this.query(pageOption);
      },
      del() {
        let checkIds = this.$refs.principalTable.getCheckData('id');
        if (!checkIds || !checkIds.length) {
          this.$message({
            message: this.$t('graduationRuth.selectTip'),
            type: 'warning'
          });
          return;
        }
        this.$delConfirm().then(res => {
          deletePrincipalManagementList({
            ids: checkIds
          }).then(res =>{
            if (res && res.code === 200) {
              this.$message({
                message: this.$t('principal.deleteSuccessTip'),
                type: 'success'
              });
              this.page.pageNum_ = 1;
              this.query();
            }
          })
        })
			  
      },
      add() {
        this.dialogIsAdd = true;
        this.dialogTitle = this.$t('common.btn.add');
        this.principalInformation = {
          name: '',
          startDate: '',
          endDate: ''
        }
        this.showPrincipalDialog = true;
        // 初始化校长姓名下拉框数据
        this.getSelectOption('', true);
      },
      editOperation(data) {
        this.dialogIsAdd = false;
        this.dialogTitle = this.$t('common.btn.edit');
        this.showPrincipalDialog = true;
        this.editId = data.id;
        this.principalInformation = {
          keyWords: `${data.name}(${data.code})`,
          startDate: data.startDate || '',
          endDate: data.endDate || '',
        }
        this.getSelectOption('', true);
      },
      close() {
        this.showPrincipalDialog = false;
      },
      confirm(name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            this.ok();
          } else {
            return false;
          }
        });
      },
      ok() {
        let startT = this.formateTimeToStr(this.principalInformation.startDate);
        let endT = this.formateTimeToStr(this.principalInformation.endDate);
        if (endT && startT > endT) {
          this.$message.error(this.$t('principal.validStartTimeAndEndTime'));
          return;
        }
        let param = {...this.principalInformation};
        if (param.keyWords) {
          let content = param.keyWords.split('(');
          param.name = content[0];
          param.code = content[1] && content[1].substring(0, content[1].length - 1) || '';
          delete param.keyWords;
        }
        let promise, msg;
        if (this.dialogIsAdd) {
          msg = this.$t('principal.addSuccessTip');
          promise = addPrincipalManagementList(param);
        }else {
          msg = this.$t('principal.editSuccessTip');
          param.id = this.editId;
          promise = updatePrincipalManagementList(param);
        }
        promise.then(res => {
          if (res && res.code === 200) {
            this.$message({
              message: msg,
              type: 'success'
            });
            this.showPrincipalDialog = false;
            this.query();
          }
        }).catch(error =>{
          if (error && error.message) {
            this.$message({
              message: error.message,
              type: 'error'
            });
          }
        })
      },
      formateTimeToStr(time){
        let timeStr = '';
        if (time) {
          time = time.replace(/-/g, '/');
          let newTime = new Date(time);
          timeStr = newTime.getTime();
        }
        return timeStr;
      },
      selectable(row, index) {
        let currentTime = new Date().getTime();
        let startTime = this.formateTimeToStr(row.startDate);
        let endTime = this.formateTimeToStr(row.endDate);
        if (currentTime >= startTime &&  (currentTime <= endTime  || !endTime)) {
          return false;
        }else {
          return true;
        }
      },
      getSelectOption(val, initFlag) {
        if (val || initFlag) {
          this.loading = true;
          findTeacherInfoList({
            condition: val,
            pageNum_: 1,
            pageSize_: 20
          }).then(res =>{
            this.loading = false;
            if (res && res.code === 200) {
              let list = res.data && res.data.list || [];
              let options = [];
              list.forEach((item, index) =>{
                options.push({
                  key: index,
                  label: `${item.name}(${item.code})`
                })
              })
              this.selectOptions = options;
              initFlag && (this.initSelectOptions = options);
            }
          }).catch(() =>{
            this.loading = false;
            this.selectOptions = [];
          })
        }else {
          this.selectOptions = this.initSelectOptions || [];
        }
      }
    }
  }
</script>
<style lang="scss"></style>